﻿using System;
using System.Collections;
using System.Collections.Generic;

using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
public class TileContainer : MonoBehaviour
{
    public Vector2 tileOffset = new Vector2(0f, 0f);
    public float tileSize = 1f;
    
    public TileObject[,] tiles;

    public int maxX;
    public int maxY;

    private void Start()
    {
        Init();
    }

    public void Init()
    {
        if (tiles != null)
            return;
        
        if (tiles == null)
        {
            tiles = new TileObject[maxX, maxY];
        }

        for (int i = 0; i < maxX; ++i)
        {
            for (int j = 0; j < maxY; ++j)
            {
                tiles[i, j] = transform.GetChild(i * maxX + j).GetComponent<TileObject>();
                tiles[i, j].Init();
            }
        }
    }

    public TileObject GetTileObject(int x, int y)
    {
        return tiles[x, y];
    }
#if UNITY_EDITOR
    public void CreateMap()
    {
        int x = maxX;
        int y = maxY;
        
        for (int i = transform.childCount - 1; i >= 0; --i)
        {
            DestroyImmediate(transform.GetChild(i).gameObject);
        }
        
        tiles = new TileObject[x, y];

        for (int i = 0; i < x; ++i)
        {
            for (int j = 0; j < y; ++j)
            {

                GameObject prefab =
                    AssetDatabase.LoadAssetAtPath<GameObject>("Assets/Development/Gameplay/Prefabs/tile_0_0.prefab");
                var tGO = GameObject.Instantiate(prefab, transform);
                tGO.name = "tile_" + i + "_" + j;

               

                var tileObject = tGO.GetComponent<TileObject>();
                tileObject.CreateTileObject(this, i, j);
            }
        }
    }
#endif
    public List<T> GetContentList<T>() where T: BaseContent
    {
        List<T> result = new List<T>();
        foreach (var tile in tiles)
        {
            if (tile.content != null && tile.content is T)
            {
                result.Add(tile.content as T);
            }
        }

        return result;
    }
}
